package com.jic.market.impl.rest.discount.processor;

import com.alibaba.fastjson.JSON;
import com.jic.market.common.util.Money;
import com.jic.market.entity.DiscountOrderDetail;
import com.jic.market.entity.PromotionRuleEntity;
import com.jic.market.enums.DiscountAmountServiceOperateEnum;
import com.jic.market.impl.rest.discount.model.ConditionDiscountModel;
import com.jic.market.impl.rest.discount.model.GoodsDetailModel;
import com.jic.market.mapper.DiscountOrderDetailMapper;
import com.jic.market.mapper.PromotionRuleEntityMapper;
import com.jic.market.request.rest.discount.DiscountBaseRequest;
import com.jic.market.request.rest.discount.DiscountCancelRequest;
import com.jic.market.request.rest.discount.DiscountOrderPayRequest;
import com.jic.market.request.rest.discount.DiscountQueryRequest;
import com.jic.market.response.rest.discount.GiftDetail;
import com.jic.market.service.rest.discount.GiftService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 满量-赠
 * @author yinhaijun
 * @date: 2020/5/7
 */
@Slf4j
@Service("GiftFullNumProcessor")
public class GiftFullNumProcessor extends AbstractConditionDiscountProcessor {
    @Autowired
    private PromotionRuleEntityMapper promotionRuleEntityMapper;
    @Autowired
    private GiftService giftService;
    @Autowired
    private DiscountOrderDetailMapper discountOrderDetailMapper;
    @Override
    public ConditionResult isCondition(ConditionDiscountModel conditionDiscountModel, Map<String, GoodsDetailModel> goodsDetailModelMap, Object request, DiscountAmountServiceOperateEnum operate) {
        if(!checkPromotion(((DiscountBaseRequest)request).getThirdUserId(), ((DiscountBaseRequest)request).getAdminOperate().getChildId().toString(), conditionDiscountModel.getChannelCodes(), conditionDiscountModel.getPromotionMemberGradeList())){
            return new ConditionResult(false, "满量赠计算"+conditionDiscountModel.getPromotionCode()+"会员等级校验未通过");
        }
        AtomicReference<Long> countValidNum = new AtomicReference<>(0L);
        List<String> thirdSkuIdList = conditionDiscountModel.getThirdSkuIdList();
        thirdSkuIdList.forEach((thirdSkuId)->{
            GoodsDetailModel goodsDetailModel = goodsDetailModelMap.get(thirdSkuId);
            countValidNum.set(countValidNum.get() + goodsDetailModel.getNum());
        });

        // 超出购买按原价处理
        List<PromotionRuleEntity> promotionRuleEntityList = promotionRuleEntityMapper.queryByPromotionId(Long.parseLong(conditionDiscountModel.getPromotionId()));
        PromotionRuleEntity promotionRuleEntity = super.getFlightPromotionRuleEntity(new BigDecimal(countValidNum.get()), promotionRuleEntityList, 3);
        // 不优惠处理
        if(null == promotionRuleEntity){
            return new ConditionResult(false, "满量赠无优惠");
        }
        // 最终匹配成功需要乘的倍数
        Long overlayAppNum = getBeiSu(conditionDiscountModel, new BigDecimal(countValidNum.get()), promotionRuleEntity);

        // 查询出所有的赠送商品
        List<GiftDetail> giftDetailList = giftService.getGiftDetails(conditionDiscountModel.getPromotionId(), conditionDiscountModel.getPromotionCode(), ((DiscountBaseRequest) request).getThirdUserId(), promotionRuleEntity, overlayAppNum);
        if(!giftDetailList.isEmpty()){
            ConditionResult conditionResult = new ConditionResult(true, "有优惠");
            conditionResult.setObject(giftDetailList);
            Map<String, List<GiftDetail>> giftMap = new HashMap<>();
            giftMap.put(conditionDiscountModel.getPromotionCode(),giftDetailList );
            log.info("------------------------"+ JSON.toJSONString(giftMap));
            return conditionResult;
        }
        return null;
    }

    @Override
    public void queryShoppingCartAfter(ConditionResult conditionResult, ConditionDiscountModel conditionDiscountModel, Map<String, GoodsDetailModel> goodsDetailModelMap, Object request){
        List<GiftDetail> giftDetailList = (List<GiftDetail>) conditionResult.getObject();
        conditionDiscountModel.setGiftDetailList(giftDetailList);
    }

    @Override
    public void querySettlementAfter(ConditionResult conditionResult, ConditionDiscountModel conditionDiscountModel, Map<String, GoodsDetailModel> goodsDetailModelMap, Object request){
        List<GiftDetail> giftDetailList = (List<GiftDetail>) conditionResult.getObject();
        DiscountQueryRequest discountQueryRequest = (DiscountQueryRequest) request;
        Map<String, List<GiftDetail>> giftMap = discountQueryRequest.getGiftMap();
        if(null != giftMap && !giftMap.isEmpty()){
            List<GiftDetail> giftDetailList1 = giftService.getMixedGiftDetails(giftMap.get(conditionDiscountModel.getPromotionCode()), giftDetailList);
            conditionDiscountModel.setGiftDetailList(giftDetailList1);
        }
    }

    @Override
    public void createAfter(ConditionDiscountModel conditionDiscountModel, Map<String, GoodsDetailModel> goodsDetailModelMap, Object request){


    }

    @Override
    public void payAfter(ConditionDiscountModel conditionDiscountModel, Map<String, GoodsDetailModel> goodsDetailModelMap, Object request){
        List<GiftDetail> giftDetailList = conditionDiscountModel.getGiftDetailList();
        DiscountOrderDetail discountOrderDetailQ = new DiscountOrderDetail();
        discountOrderDetailQ.setOrderNo(((DiscountOrderPayRequest) request).getOrderNo());
        List<DiscountOrderDetail> discountOrderDetailList =  discountOrderDetailMapper.query(discountOrderDetailQ);
        giftService.issuanceGift(giftDetailList, discountOrderDetailList.get(0).getThirdUserId());
    }

    @Override
    public void isAllCancelAfter(ConditionDiscountModel conditionDiscountModel, Map<String, GoodsDetailModel> goodsDetailModelMap, Object request) {
        List<GiftDetail> giftDetailList = conditionDiscountModel.getGiftDetailList();
        DiscountOrderDetail discountOrderDetailQ = new DiscountOrderDetail();
        discountOrderDetailQ.setOrderNo(((DiscountCancelRequest) request).getOrderNo());
        List<DiscountOrderDetail> discountOrderDetailList =  discountOrderDetailMapper.query(discountOrderDetailQ);
        giftService.recycleGift(giftDetailList, discountOrderDetailList.get(0).getThirdUserId());
    }

    private Long getBeiSu(ConditionDiscountModel promotionAmountModel, BigDecimal condition, PromotionRuleEntity promotionRuleEntity) {
        Long overlayAppNum = 1L;
        if(promotionAmountModel.getOverlayAppFlag()){
            BigDecimal divideInt = Money.divideInt(condition, new BigDecimal(promotionRuleEntity.getConditionValue()));
            if(divideInt.compareTo(new BigDecimal(promotionAmountModel.getOverlayAppNum())) == 1){
                overlayAppNum = Long.valueOf(promotionAmountModel.getOverlayAppNum());
            }else {
                overlayAppNum = Long.valueOf(divideInt.intValue());
            }
        }
        return overlayAppNum;
    }

}
